package com.kotlin.myapplication.base

import android.os.Bundle
import android.view.View
import android.content.Intent
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import com.kotlin.myapplication.mananger.AppManager
import androidx.fragment.app.Fragment


/**
 *@lil
 *@创建时间 2019/11/4 16:06
 *@描述
 */


/***************************************************************************
 *
 * 生命周期 场景演示 :
 *
 * 切换到该Fragment
 * onAttach-onCreate-onCreateView-onActivityCreated-onStart-onResume
 *
 * 屏幕灭掉 onPause-onSaveInstanceState-onStop
 *
 * 屏幕解锁 onStart-onResume
 *
 * 切换到其他Fragment onPause-onStop-onDestroyView
 *
 * 切换回本身的Fragment onCreateView-onActivityCreated-onStart-onResume
 *
 * 回到桌面 onPause-onSaveInstanceState-onStop
 *
 * 回到应用 onStart-onResume
 *
 * 退出应用 onPause-onStop-onDestroyView-onDestroy-onDetach
 ***************************************************************************/

abstract class BaseFragment : Fragment() {

    var v: View? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // setRetainInstance(true);// 保存状态
        if (null != savedInstanceState && null != activity) {
            AppManager.finishAllActivity()
            val i = activity!!.baseContext.packageManager
                    .getLaunchIntentForPackage(activity!!.baseContext.packageName)
            i!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(i)
        } else {
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        v = getView(inflater!!, container!!)
        // 缓存的view需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。
        val parent = v!!.getParent() as? ViewGroup
        parent?.removeView(v)
//        ViewUtils.inject(this, v)

        return v

    }

    /**
     * 程序入库需要在onViewCreated添加 在onCreateView方法获取view会空指针
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(v!!)
    }

    /**
     *
     * @param inflater
     * @return 需要显示的view
     */
    abstract fun getView(inflater: LayoutInflater, parent: ViewGroup): View

    /**
     * 程序入库/UI控件注入
     */
    abstract fun initView(view: View)

    fun showToast(msg: String) {
        if (null != activity && !activity!!.isFinishing) {
            if (TextUtils.isEmpty(msg)) {
                return
            }
            Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show()
        }

    }
}